(function () {
    'use strict';

    function xpager(element, options) {
        this.element = element;
        this.options = Object.assign({}, {
            total: 0,
            totalPages: 1,
            currentPage: 1,
            pageSize: 10,
            goto: '',
            perPageLimit: [
                10, 20, 50, 100,
            ],
            firstPageText: '«',
            prevPageText: '‹',
            nextPageText: '›',
            lastPageText: '»',
            theme: '#16b777',
            showGoto: false,
            formEl: 'form',
            pageElName: 'page',
            pageSizeElName: 'page_size',
            onPageChange: function () {
                //获取当前表单的数据
                let formElement = document.querySelector(this.formEl);
                if (!formElement) {
                    return false;
                }
                let pageElement;
                if (document.querySelector('input[name="'+this.pageElName+'"]') == null) {
                    pageElement = document.createElement('input');
                    pageElement.name = this.pageElName;
                    pageElement.type = 'hidden';
                } else {
                    pageElement = document.querySelector('input[name="'+this.pageElName+'"]');
                }
                pageElement.value = this.currentPage;
                let pageSizeElement;
                if (document.querySelector('input[name="'+this.pageSizeElName+'"]') == null) {
                    pageSizeElement = document.createElement('input');
                    pageSizeElement.name = this.pageSizeElName;
                    pageSizeElement.type = 'hidden';
                } else {
                    pageSizeElement = document.querySelector('input[name="'+this.pageSizeElName+'"]');
                }
                pageSizeElement.value = this.pageSize;
                formElement.appendChild(pageElement);
                formElement.appendChild(pageSizeElement);
                formElement.submit();
            }
        }, options);
        this.init();
        this.xpagerStyle();
    };

    xpager.prototype.init = function () {
        this.render();
    };

    xpager.prototype.render = function () {
        let totalPages = Math.ceil(this.options.total / this.options.pageSize);
        this.options.totalPages = totalPages;
        if (parseInt(this.options.goto) > 0) {
            this.options.currentPage = parseInt(this.options.goto);
        }
        let perOptions = '';
        for (let i = 0; i < this.options.perPageLimit.length; i++) {
            perOptions += '<option value="' + this.options.perPageLimit[i] + '">' + this.options.perPageLimit[i] + '条/页</option>';
        }
        // 控制显示的页码数量，最多显示10个页码
        const maxPageNumbers = 10;
        const halfMaxPageNumbers = Math.floor(maxPageNumbers / 2);
        let startPage = Math.max(1, this.options.currentPage - halfMaxPageNumbers);
        let endPage = Math.min(totalPages, startPage + maxPageNumbers - 1);
        if (endPage - startPage < maxPageNumbers - 1) {
            startPage = Math.max(1, endPage - maxPageNumbers + 1);
        }

        let pageOptions = '';
        if (this.options.currentPage != 1 && totalPages > maxPageNumbers) {
            pageOptions += '<li class="xpager-first-page">' + this.options.firstPageText + '</li><li class="xpager-prev-page">' + this.options.prevPageText + '</li>';
        }
        for (let i = startPage; i <= endPage; i++) {
            if (this.options.currentPage == i) {
                pageOptions += '<li class="xpager-page xpager-active">' + i + '</li>';
            } else {
                pageOptions += '<li class="xpager-page">' + i + '</li>';
            }
        }
        if (this.options.currentPage != totalPages && totalPages > maxPageNumbers) {
            pageOptions += '<li class="xpager-next-page">' + this.options.nextPageText + '</li><li class="xpager-last-page">' + this.options.lastPageText + '</li>'
        }
        let innerHTML = `<div class="xpgaer-summary">
        <div class="xpager-total">
            共<span>`+ this.options.total + `</span>
        </div>
        <span class="xpager-perpage">
            <select>
                `+ perOptions + `
            </select>
        </span>
    </div>
    <div class="xpager-pages">
        <ul>
            `+ pageOptions + `
        </ul>
    </div>`;
        if (this.options.total > 0 && this.options.showGoto) {
            innerHTML += `<div class="xpager-fast">
            <span>到</span>
            <input type="text" class="xpager-input" value="`+ this.options.goto + `" />
            <button class="xpager-btn">确定</button>
        </div>`;
        }
        this.element.innerHTML = innerHTML;
        // 更新下拉列表的选中项
        const perPageSelect = this.element.querySelector('.xpager-perpage select');
        perPageSelect.value = this.options.pageSize;
        this.bindEvents();
    };

    xpager.prototype.handlePerPageChange = function () {
        var perPageSelect = this.element.querySelector('.xpager-perpage select');
        this.options.pageSize = parseInt(perPageSelect.value);
        this.options.currentPage = 1; // 选择每页条数后回到第一页
        this.render(); // 重新渲染分页
        this.options.onPageChange(this.options.currentPage);
    };

    xpager.prototype.handleGotoPage = function () {
        var inputElement = this.element.querySelector('.xpager-input');
        var page = parseInt(inputElement.value);
        if (!isNaN(page) && page >= 1 && page <= this.options.totalPages) {
            this.options.currentPage = page;
            this.options.goto = page;
            this.render();
            this.options.onPageChange(this.options.currentPage);
        }
    };

    xpager.prototype.bindEvents = function () {
        var self = this; // 保存当前对象的引用
        var selectElement = this.element.querySelector('.xpager-perpage select');
        // 添加下拉列表的选择事件监听器
        selectElement.addEventListener('change', function (event) {
            self.handlePerPageChange();
        });
        //添加btn
        var btnElement = this.element.querySelector('button');
        if (btnElement != null) {
            btnElement.addEventListener('click', function (event) {
                self.handleGotoPage();
            });
            var inputElement = this.element.querySelector('input');
            inputElement.addEventListener('input', function () {
                if (!/^[1-9]\d*$/.test(this.value)) {
                    this.value = ''; // 清除输入
                }
            });
        }
        var container = this.element.querySelector('.xpager-pages');
        container.addEventListener('click', function (event) {
            event.preventDefault(); // 阻止默认行为
            var target = event.target;
            if (target.classList.contains('xpager-page')) {
                // 点击了页码按钮
                var page = parseInt(target.textContent);
                self.options.goto = '';
                self.options.currentPage = page;
                self.render(); // 更新页码样式
                self.options.onPageChange(self.options.currentPage);
            } else if (target.classList.contains('xpager-prev-page')) {
                // 点击了上一页按钮
                self.prevPage();
            } else if (target.classList.contains('xpager-next-page')) {
                // 点击了下一页按钮
                self.nextPage();
            } else if (target.classList.contains('xpager-first-page')) {
                // 点击了首页按钮
                self.firstPage();
            } else if (target.classList.contains('xpager-last-page')) {
                // 点击了末页按钮
                self.lastPage();
            }
        });

    };

    xpager.prototype.firstPage = function () {
        this.options.currentPage = 1;
        this.options.goto = '';
        this.render();
        this.options.onPageChange(this.options.currentPage);
    };
    xpager.prototype.lastPage = function () {
        this.options.currentPage = this.options.totalPages;
        this.options.goto = '';
        this.render();
        this.options.onPageChange(this.options.currentPage);
    };

    xpager.prototype.prevPage = function () {
        this.options.goto = '';
        if (this.options.currentPage > 1) {
            this.options.currentPage--;
            this.render();
            this.options.onPageChange(this.options.currentPage);
        }
    };

    xpager.prototype.nextPage = function () {
        this.options.goto = '';
        var currentPage = this.options.currentPage;
        var totalPages = this.options.totalPages;
        if (currentPage < totalPages) {
            this.options.currentPage++;
            this.render();
            this.options.onPageChange(this.options.currentPage);
        }
    };

    xpager.prototype.xpagerStyle = function () {
        const styleElement = document.createElement('style');
        styleElement.textContent = `.xpager-container {
            font-size: 13;
            text-align: right;
            padding-right: 10px;
            position: relative;
            margin-top: 10px;
            min-height: 30px;
        }
        .xpgaer-summary{
            position: absolute;
            left: 10px;
        }
        .xpager-total,
        .xpager-perpage,
        .xpager-pages,
        .xpager-fast {
            display: inline-block;
        }
    
        .xpager-total {
            font-size: 13px;
        }
    
        .xpager-pages ul {
            font-size: 0;
        }
        .xpager-pages ul li {
            display: inline-block;
            border: solid 1px #eee;
            min-width: 13px;
            font-size: 13px;
            line-height:13px;
            padding: 8px 10px;
            text-align: center;
            cursor: pointer;
        }
    
        .xpager-pages ul li:not(:first-child) {
            border-left: none;
        }
        .xpager-pages ul li:not('.xpager-active'):hover {
            color: `+ this.options.theme + `;
        }
        .xpager-pages ul .xpager-active {
            background-color:`+ this.options.theme + `;
            color: #fff;
            border-color: `+ this.options.theme + `;
            cursor: auto;
        }
    
        .xpager-input {
            display: inline-block;
            border: solid 1px #eee;
            max-width: 40px;
            font-size: 13px;
            line-height:13px;
            padding: 5px 0px;
            text-align: center;
        }
    
        .xpager-input:focus {
            outline: none;
        }
    
        .xpager-fast {
            margin-left: 30px;
            font-size: 13px;
        }
    
        .xpager-fast button {
            display: inline-block;
            cursor: pointer;
            background-color: #fff;
            border: solid 1px #eee;
            font-size: 13px;
            line-height:13px;
            padding: 6px 10px;
        }
    
        .xpager-perpage select {
            border: solid 1px #eee;
            outline: none;
            height: 28px;
            border-radius: 2px;
            cursor: pointer;
        }`;
        document.head.appendChild(styleElement);
    };
    window.xpager = xpager;
}());